package cn.huobi.pet.consumer;

import cn.huobi.basic.config.BussinessException;
import cn.huobi.order.domain.OrderPetAcquisition;
import cn.huobi.order.service.IOrderPetAcquisitionService;
import cn.huobi.pet.domain.RejectSearchMasterLog;
import cn.huobi.pet.domain.SearchMasterMsg;
import cn.huobi.pet.service.IRejectSearchMasterLogService;
import cn.huobi.pet.service.ISearchMasterMsgService;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * rocketmq 消息监听，@RocketMQMessageListener中的selectorExpression为tag，默认为*
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = "searchMaster_order_topic",selectorExpression="*",consumerGroup = "pethome-server-message")
public class RocketMQMsgListener implements RocketMQListener<MessageExt> {

    @Autowired
    private IOrderPetAcquisitionService orderPetAcquisitionService;
    @Autowired
    private ISearchMasterMsgService searchMasterMsgService;
    @Autowired
    private IRejectSearchMasterLogService rejectSearchMasterLogService;

    @Override
    public void onMessage(MessageExt message) {
        byte[] body = message.getBody();
        String msg = new String(body, CharsetUtil.UTF_8);
        Long id = Long.valueOf(msg);
        OrderPetAcquisition orderPetAcquisition = orderPetAcquisitionService.findById(id);
        if (orderPetAcquisition == null){
            throw new BussinessException("该订单不存在");
        }
        if (orderPetAcquisition.getState() == 0){
            orderPetAcquisition.setState(-1);
            orderPetAcquisitionService.update(orderPetAcquisition);

            SearchMasterMsg searchMasterMsg = searchMasterMsgService.findById(orderPetAcquisition.getSearchMasterMsgId());
            searchMasterMsg.setState(1);
            searchMasterMsg.setShopId(null);
            searchMasterMsgService.update(searchMasterMsg);

            RejectSearchMasterLog rejectSearchMasterLog = new RejectSearchMasterLog();
            rejectSearchMasterLog.setEmpId(orderPetAcquisition.getEmpId());
            rejectSearchMasterLog.setMsgId(searchMasterMsg.getId());
            rejectSearchMasterLog.setNote("寻主消息订单超时未处理！");
            rejectSearchMasterLogService.add(rejectSearchMasterLog);
        }

        log.info("接收到消息：{}", msg);
    }

}